import * as api from '@/api/exam';

const state = {
  examList: [],
  currentExam: null,
  myExams: [],
  examResults: [],
  passedSubjects: {
    subject1: false,
    subject2: false,
    subject3: false,
    subject4: false
  }
};

const mutations = {
  SET_EXAM_LIST(state, exams) {
    state.examList = exams;
  },
  SET_CURRENT_EXAM(state, exam) {
    state.currentExam = exam;
  },
  SET_MY_EXAMS(state, exams) {
    state.myExams = exams;
  },
  SET_EXAM_RESULTS(state, results) {
    state.examResults = results;

    // 计算考试通过情况
    const passedSubjects = {
      subject1: false,
      subject2: false,
      subject3: false,
      subject4: false
    };

    results.forEach(result => {
      if (result.is_passed && result.exam) {
        passedSubjects[result.exam.exam_type] = true;
      }
    });

    state.passedSubjects = passedSubjects;
  }
};

const actions = {
  // 获取考试列表
  getExams({ commit }) {
    return new Promise((resolve, reject) => {
      api.getExams()
        .then(res => {
          commit('SET_EXAM_LIST', res.data);
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 获取考试详情
  getExam({ commit }, id) {
    return new Promise((resolve, reject) => {
      api.getExam(id)
        .then(res => {
          commit('SET_CURRENT_EXAM', res.data);
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 报名考试
  registerExam({ commit }, examId) {
    return new Promise((resolve, reject) => {
      api.registerExam(examId)
        .then(res => {
          resolve(res);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 取消考试报名
  cancelExamRegistration({ commit }, examId) {
    return new Promise((resolve, reject) => {
      api.cancelExamRegistration(examId)
        .then(res => {
          resolve(res);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 获取我的考试列表
  getMyExams({ commit }) {
    return new Promise((resolve, reject) => {
      api.getMyExams()
        .then(res => {
          commit('SET_MY_EXAMS', res.data);
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 获取我的考试成绩
  getMyExamResults({ commit }) {
    return new Promise((resolve, reject) => {
      api.getMyExamResults()
        .then(res => {
          commit('SET_EXAM_RESULTS', res.data);
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};

const getters = {
  examList: state => state.examList,
  currentExam: state => state.currentExam,
  myExams: state => state.myExams,
  examResults: state => state.examResults,
  passedSubjects: state => state.passedSubjects,
  upcomingExams: state => state.examList.filter(item => item.status === 'upcoming').slice(0, 3)
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};